﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Security;
using eTerm.MsSql.DbProvider;
using eTerm.Platform.Common;
using System.Text;
using System.Web.Script.Serialization;

namespace eTerm.Platform.Web.ISAPI
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class SysUserAPI : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/xml";

            string action = context.Request["Action"];

            switch (action.ToLower().Trim()) { 
                case "logout":
                    Logout();
                    break;
                case @"selectcabin":
                    SelectCabin(context);
                    break;
                case @"deletecabin":
                    DeleteCabin(context);
                    break;
                case @"approverequire":
                    ApproveRequire(context);
                    break;
                case @"rejectrequire":
                    RejectRequire(context);
                    break;
                case "updatepassword":
                    UpdatePassword(context.Request.Form["Password"],context);
                    break;
                case "menu":
                    UserMenu(context);
                    break;
                case @"addpermission":
                    AssignPermission(context);
                    break;
                case "completedetr":
                    CompleteDETR(context.Request.Form["ID"]);
                    break;
                case "permissiontree":
                    OutputPermission(context);
                    break;
                case "cancelrequire":
                    CancelRequire(context);
                    break;
                default:
                    break;
            }
            //HttpContext.Current.u
            context.Response.End();
        }

        private void RejectRequire(HttpContext context) {
            long ID = long.Parse(context.Request.Form["ID"]);
            PnrRequire require = PnrRequire.All().FirstOrDefault(l => l.Id == ID);
            require.StatusId = (int)PNRRequireStatus.REJECT;
            require.Save();
        }

        private void ApproveRequire(HttpContext context) {
            long ID = long.Parse(context.Request.Form["ID"]);
            PnrRequire require = PnrRequire.All().FirstOrDefault(l => l.Id == ID);
            require.StatusId = (int)PNRRequireStatus.APPROVED;
            require.Save();
        }

        private void CancelRequire(HttpContext context) {
            long ID =long.Parse( context.Request.Form["ID"]);
            PnrRequire require = PnrRequire.All().FirstOrDefault(l => l.Id == ID);
            require.StatusId = (int)PNRRequireStatus.CANCELD;
            require.Save();
        }

        private void DeleteCabin(HttpContext context) { 
            long SegmentID = long.Parse(context.Request.Form["RequireID"]);
            int CabinID = int.Parse(context.Request.Form["CabinID"]);
            //new PnrRequireCode().Delete(l => (l.CabinId == CabinID) && (l.SegmentId == SegmentID));
        }

        private void SelectCabin(HttpContext context) {
            long SegmentID = long.Parse(context.Request.Form["RequireID"]);
            int CabinID = int.Parse(context.Request.Form["CabinID"]);

            //new PnrRequireCode() { CabinId = CabinID, SegmentId = SegmentID }.Save();

        }

        private void AssignPermission(HttpContext context) {
            int UID = int.Parse(context.Request.Form["UID"]);
            string PID = (context.Request.Form["PID"]);
            SysAuthority model= SysAuthority.FirstOrDefault(l => l.AuthorityCode == PID);
            if (!SysUserAuthority.Exists(l => l.UserId == UID && l.AuthorityCode == model.ParentCode))
                new SysUserAuthority() { AuthorityCode = model.ParentCode ,UserId = UID}.Save();

            new SysUserAuthority().Delete(l => l.UserId == UID && l.AuthorityCode == PID);
            new SysUserAuthority() { AuthorityCode=PID, UserId=UID }.Save();
        }

        private void OutputPermission(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            TreeNode root = LoopTree(new TreeNode() { id = null },context.Request["UID"]);

            context.Response.Write(JsonResult(root.children));
        }

        /// <summary>
        /// 生成JSON数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private string JsonResult(object data)
        {
            if (data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return (serializer.Serialize(data));
            }
            return string.Empty;
        }




        protected TreeNode LoopTree(TreeNode Parent,string UID)
        {
            int UserID = int.Parse(UID);
            Parent.children = new List<TreeNode>();
            var items =
                SysAuthority.All()
                .SelectMany(r => SysUserAuthority.All().Where(sr => sr.UserId == UserID && sr.AuthorityCode == r.AuthorityCode).DefaultIfEmpty(), (l, r) => new { l, r })
                .Where(l => l.l.ParentCode == Parent.id /*&& string.IsNullOrEmpty(l.r.AuthorityCode)*/).Select(l => new { l.l, @checked = (!string.IsNullOrEmpty(l.r.AuthorityCode)) })
                .ToList();
            items.Select(l => new TreeNode() { id = l.l.AuthorityCode, text = l.l.AuthorityName, attributes = new { url = l.l.AuthorityUrl }, children = new List<TreeNode>(), iconCls = l.l.Icon, @checked = l.@checked, state = @"open" }).ToList().ForEach(l =>
            {
                LoopTree(l, UID);
                Parent.children.Add(l);
                //    //Parent.LSTFK_SYS_AUTH_REFERENCE_SYS_AUTH.Add(l);
            });
            //items.Select(l => new TreeNode() { id = l.l.AuthorityCode, text = l.l.AuthorityName, attributes = new { url = l.l.AuthorityUrl }, children = new List<TreeNode>(), iconCls = l.l.Icon, @checked=l.@checked, state = @"open" })
            //    .ToList().ForEach(l =>
            //{
            //    LoopTree(l,UID);
            //    Parent.children.Add(l);
            //    //Parent.LSTFK_SYS_AUTH_REFERENCE_SYS_AUTH.Add(l);
            //});
            return Parent;
        }

        private void CompleteDETR(string ID) {
            if (string.IsNullOrEmpty(ID)) return;

            PnrDetr model = PnrDetr.FirstOrDefault(l => l.Id == long.Parse(ID));
            if (model == null) return;
            new PnrHistory() { DetrInfo = string.Empty, NewStatusId = model.StatusId, SourceStatusId = (int)DetrStatus.COMPLETED , ProcessDate = DateTime.Now, TicketNoId = model.Id}.Save();
            model.StatusId =(model.StatusId&(int)DetrStatus.BEFORECOMPARE) | (int)DetrStatus.COMPLETED;
            model.Save();
        }

        private void UpdatePassword ( string password,HttpContext context) {
            int UID = int.Parse(context.User.Identity.Name);
            SysUser model = SysUser.FirstOrDefault(l => l.UserId == UID);
            model.Password = Encrypt.MD5Encrypt(password);
            model.Save();
        }

        private void Logout() {
            FormsAuthentication.SignOut();
        }


        private void UserMenu(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            int UID = int.Parse(context.User.Identity.Name);
            StringBuilder xmlResult = new StringBuilder(@"{""menus"":[");

            List<SysAuthority> items =  SysUserAuthority.All()
                .Where(l => l.UserId == UID)
                .Join(SysAuthority.All(), l => l.AuthorityCode, r => r.AuthorityCode, (l, r) => r).Where(l=>!string.IsNullOrEmpty(l.AuthorityUrl))
                .Distinct().ToList();

            UserMenu(xmlResult, items,null,1);
                
            xmlResult.Append(@"
]}");
            context.Response.Write(xmlResult.ToString());
        }

        private void UserMenu(StringBuilder sb,List<SysAuthority> Items,string parentCode,int level) {
            if (Items.Count(l => l.ParentCode == parentCode) == 0) { sb.Remove(sb.Length - 1, 1); return; }
            int count = 0;
            Items.Where(l => l.ParentCode == parentCode).OrderBy(l => l.AuthorityCode).ToList().ForEach(l => {
                sb.AppendFormat(@"
    {3}{{""menuid"":""{0}"",""icon"":""{4}"", ""menuname"":""{1}"",""url"":""{2}"" ", l.AuthorityCode, l.AuthorityName, l.AuthorityUrl,count++==0?@"":@",",l.Icon);

                if (Items.Count(c => c.ParentCode == l.AuthorityCode) > 0)
                {
                    sb.Append(@",""menus"":[");
                    UserMenu(sb, Items, l.AuthorityCode,level+1);
                    sb.Append(@"]");
                }

                sb.Append(@"
    }");
            });
            //sb.Remove(sb.Length - 1, 1);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


}
